package com.lex.controller;

import com.lex.common.annoatation.SysLog;
import com.lex.common.api.CommonResult;
import com.lex.common.enums.BusinessType;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.lex.util.MyContext;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {
    public static String UPLOAD_DIRECTORY = System.getProperty("user.dir") + File.separator + "uploads";
    public final String[] ALLOWED_FILE_MINE_TYPES = new String[]{
            "image/jpeg",
            "image/png",
            "image/gif",
            "image/bmp",
            "image/webp",
            "image/tiff",
    };
    @Operation(summary = "本地上传文件")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @SysLog(title = "本地上传文件", businessType = BusinessType.INSERT)
    public CommonResult upload(@RequestParam("file") MultipartFile[] files) throws IOException {
        //使用MultipartFile[]完成上传文件
        List<String> fileNames = new ArrayList<>();
        for (MultipartFile file : files) {
            //获取文件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //读取文件二进制内容，判断是否为图片
            Tika tika =new Tika();
            String real_file_type = tika.detect(file.getBytes());
            log.info("文件类型为：" + real_file_type);
            if (!Arrays.asList(ALLOWED_FILE_MINE_TYPES).contains(real_file_type)) {
                return CommonResult.failed("文件类型不合法");
            }
            //上传文件
            if (file.getSize() <= 0) {
                continue;
            }
            final String newFileName = save(file);
            //file.transferTo(new File("D:/upload/"+fileName));
            fileNames.add(newFileName);
        }
        return CommonResult.success(fileNames);
    }
    private String save(MultipartFile file) throws IOException{
        String newFileName = genNewFileName(file.getOriginalFilename());
        //根据当前日期创建目录
        String username = MyContext.getCurrentUserName();
        //获取当前日期 yyyyMMdd
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String datePath = sdf.format(date);
        String new_upload_path = UPLOAD_DIRECTORY+"\\"+ username+"\\"+ datePath;
        Path path = Paths.get(new_upload_path);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
        final Path filePath = Paths.get(new_upload_path, newFileName);
        Files.write(filePath, file.getBytes());
        System.out.println("file saved to: " + filePath);
        return filePath.toString();
    }
    private String genNewFileName(String filename) {
        String filenameFormat = "%s.%s";
        return String.format(filenameFormat,
                UUID.randomUUID().toString().replace("-", "").substring(8),
                FilenameUtils.getExtension(filename)
        );

    }
}
